package com.sunday.aomicaichang.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.UploadUtils;
import com.sunday.common.widgets.explosionfield.ExplosionField;
import com.sunday.common.widgets.gridview.NoScrollGridView;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.adpter.MakeCommentImageAdapter;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.widgets.FlexibleRatingBar;
import com.sunday.member.entity.UploadImage;
import com.sunday.member.entity.order.OrderItem;
import com.sunday.member.entity.order.OrderProduct;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/7.
 */

public class AssessActivity extends BaseActivity {
    @Bind(R.id.ly_item)
    LinearLayout lyItem;
    @Bind(R.id.btn_commit)
    TextView btnCommit;

    private List<MakeCommentImageAdapter> assessAdapter=new ArrayList<>();

    private ArrayList<String> selectPath;
    private ExplosionField mExplosionField;
    private long orderId;
    private List<String> productIds=new ArrayList<>();
    private List<String> contents=new ArrayList<>();
    private List<String> scores=new ArrayList<>();

    private List<String> netStr=new ArrayList<>();
    private ArrayList<String> img=new ArrayList<>();
    private OrderItem order;

    private int maxImageCount = 3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_assess);
        ButterKnife.bind(this);
        order = (OrderItem) getIntent().getSerializableExtra("order");
        if(netStr!=null)
            netStr.clear();
        if(img!=null)
            img.clear();
        lyItem.removeAllViews();
        if (order.getProducts().size() != 0) {
            for(int j=0;j<order.getProducts().size();j++){
                long productId=order.getProducts().get(j).getId();
                productIds.add(String.valueOf(productId));
                OrderProduct orderProduct=order.getProducts().get(j);
                View v1 = LayoutInflater.from(mContext).inflate(R.layout.item_assess, null);
                ImageView imgTop= (ImageView) v1.findViewById(R.id.img_top);
                TextView tvName= (TextView) v1.findViewById(R.id.tv_name);
                FlexibleRatingBar flexibleRatingBar= (FlexibleRatingBar) v1.findViewById(R.id.flexibleRatingBar);
                EditText editText= (EditText) v1.findViewById(R.id.edit_text);
                NoScrollGridView noScrollGridView= (NoScrollGridView) v1.findViewById(R.id.images);
                Picasso.with(mContext)
                        .load(orderProduct.getImage())
                        .error(R.mipmap.ic_product)
                        .into(imgTop);
                tvName.setText(orderProduct.getName());
                final List<Object> dataSet = order.getProducts().get(j).getImages();
                dataSet.add(R.mipmap.add);
                final MakeCommentImageAdapter adapter = new MakeCommentImageAdapter(mContext,dataSet);
                noScrollGridView.setAdapter(adapter);
                assessAdapter.add(adapter);
                lyItem.addView(v1);
                final int index = j;
                adapter.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = (int)v.getTag();

                        if(v.getId()==R.id.delete_image){
                            dataSet.remove(position);
                            int k=0;
                            int num = 0;
                            for(int pos=0;pos<index+1;pos++){
                                View child = lyItem.getChildAt(pos);
                                NoScrollGridView noScrollGridView = (NoScrollGridView) child.findViewById(R.id.images);
                                num=noScrollGridView.getChildCount();
                                k=k+num-1;
                            }
                            if(index!=0) {
                                k = k - (3 - position);
                                path.remove(k);
                            }else {
                                path.remove(position);
                            }
                            adapter.notifyDataSetChanged();
                            View view = (View)v.getTag(R.id.action0);
                            mExplosionField.explode(view);
                            return ;
                        }else{
                            if(position==dataSet.size()-1){

                                Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
                                // 是否显示拍摄图片
                                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                                // 最大可选择图片数量
                                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxImageCount-adapter.getDataSet().size()+1);
                                // 选择模式
                                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);

                                intent.putExtra("position", index);
                                startActivityForResult(intent, 0);
                            }
                        }
                    }
                });
            }
        }
        mExplosionField = ExplosionField.attach2Window(this);
        orderId = order.getId();
    }

    @OnClick(R.id.btn_commit)
    void submitComment(){
        showLoadingDialog(0);
        if(path!=null&&path.size()>0){

            uploadImg(UploadUtils.getRequestBody(path));
        }else {
            if (scores != null) {
                scores.clear();
            }
            if (contents != null) {
                contents.clear();
            }
            for (int i = 0; i < lyItem.getChildCount(); i++) {
                View child = lyItem.getChildAt(i);
                FlexibleRatingBar flexibleRatingBar = (FlexibleRatingBar) child.findViewById(R.id.flexibleRatingBar);
                NoScrollGridView noScrollGridView = (NoScrollGridView) child.findViewById(R.id.images);
                EditText editText= (EditText) child.findViewById(R.id.edit_text);
                int score = (int) flexibleRatingBar.getRating();
                if (score == 0) {
                    scores.add("5");
                } else {
                    scores.add(String.valueOf(score));
                }
                String content = editText.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    contents.add("系统默认好评");
                } else {
                    contents.add(content);
                }
                int num = noScrollGridView.getChildCount()-1;
                if (num != 0) {
                    for (int j = 0; j < num; j++) {
                        if(netStr.size()!=0||netStr!=null)
                           img.add(netStr.get(j));
                    }
                    if (num < 3) {
                        for (int j = 0; j < 3 - num; j++) {
                            img.add("noImage");
                        }
                    }
                } else {
                    for (int j = 0; j < 3; j++) {
                        img.add("noImage");
                    }
                }
            }
            commit();
        }
    }

    private void commit() {
        String images =  StringUtils.listToString(img);
        String ids =  StringUtils.listToString(productIds);
        String content =  StringUtils.listToString(contents);
        String score =  StringUtils.listToString(scores);
        showLoadingDialog(0);
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"orderId","productIds","contents","scores","images","nonce"};
        String[] str2 = new String[]{String.valueOf(orderId),ids,content,score,images, nonce};
        Call<ResultDO> call= ApiClient.getApiAdapter().comment(orderId,ids,content,score,images,nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if(netStr!=null)
                    netStr.clear();
                if(img!=null)
                    img.clear();
                dissMissDialog();
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body() != null && response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext,"评论成功");
                    finish();
                } else {

                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络错误");
            }
        });
    }
    private void uploadImg(RequestBody requestBody) {
        showLoadingDialog(0);
        Call<ResultDO<List<UploadImage>>> call= MemberClient.getApiAdapter().uploadMulti(requestBody);
        call.enqueue(new Callback<ResultDO<List<UploadImage>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<UploadImage>>> call, Response<ResultDO<List<UploadImage>>> response) {
                dissMissDialog();
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body() != null && response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext,"上传成功");
                    List<UploadImage> resultDO1 =response.body().getResult();
                    netStr = new ArrayList<>();
                    for(UploadImage item:resultDO1){
                        netStr.add(item.getHalfPath());
                    }if (scores != null) {
                        scores.clear();
                    }
                    if (contents != null) {
                        contents.clear();
                    }
                    for (int i = 0; i < lyItem.getChildCount(); i++) {
                        View child = lyItem.getChildAt(i);
                        FlexibleRatingBar flexibleRatingBar = (FlexibleRatingBar) child.findViewById(R.id.flexibleRatingBar);
                        EditText editText = (EditText) child.findViewById(R.id.edit_text);
                        NoScrollGridView noScrollGridView = (NoScrollGridView) child.findViewById(R.id.images);

                        int score = (int) flexibleRatingBar.getRating();
                        if (score == 0) {
                            scores.add("5");
                        } else {
                            scores.add(String.valueOf(score));
                        }
                        String content = editText.getText().toString();
                        if (TextUtils.isEmpty(content)) {
                            contents.add("系统默认好评");
                        } else {
                            contents.add(content);
                        }

                        int num = noScrollGridView.getChildCount()-1;

                    if (num != 0) {
                        for (int j = 0; j < num; j++) {
                            img.add(netStr.get(j));
                        }
                        if (num < 3) {
                            for (int j = 0; j < 3 - num; j++) {
                                img.add("noImage");
                            }
                        }
                    } else {
                        for (int j = 0; j < 3; j++) {
                            img.add("noImage");
                        }
                    }

                    }
//                    if (num != 0) {
//                        for (int j = 0; j < num; j++) {
//                            img.add(netStr.get(j));
//                        }
//                        if (num < 3) {
//                            for (int j = 0; j < 3 - num; j++) {
//                                img.add("noImage");
//                            }
//                        }
//                    } else {
//                        for (int j = 0; j < 3; j++) {
//                            img.add("noImage");
//                        }
//                    }
                    commit();
                } else {
                    if(netStr!=null)
                    netStr.clear();
                    if(img!=null)
                    img.clear();

                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<UploadImage>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络错误");
            }
        });
    }
    int  count = 0;
    private ArrayList<String> path=new ArrayList<>();
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data==null){
            return;
        }
        int position = data.getIntExtra("position",0);
        selectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
        int k=0;
        for(int pos=0;pos<position;pos++){
            View child = lyItem.getChildAt(pos);
            NoScrollGridView noScrollGridView = (NoScrollGridView) child.findViewById(R.id.images);
            k=k+noScrollGridView.getChildCount()-1;
        }
        if(k==0){
            path.addAll(selectPath);
        }else {
            path.addAll(k, selectPath);
        }
        final  MakeCommentImageAdapter adapter =  assessAdapter.get(position);
        final List list =  adapter.getDataSet();
        final int size = selectPath.size();
        if(size>0){
            showLoadingDialog(0);
        }
        for (int i = 0; i < size; i++) {
            Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if(msg.what==1){
                        list.add(list.size()-1,msg.obj.toString());
                    }
                    count++;
                    if(count>=size){
                        adapter.notifyDataSetChanged();
                        dissMissDialog();
                    }
                }
            };
            downUrlToPath(handler,selectPath.get(i));
        }
    }

    private void downUrlToPath(final Handler handler, final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path =  ImageUtils.getCompressImagePath(url);
                Message msg = handler.obtainMessage();
                msg.obj = path;
                msg.what  =1;
                handler.sendMessage(msg);
            }
        }).start();
    }

}
